import { Context } from "egg";

export default {
  /**
   * * 内部请求转发
   * @description 针对GET请求的地址转发，非GET请求将抛出异常
   * @example ex1：当to是字符串时，直接转发至目标地址
   * @example ex2：当to是函数时，直接转发至to的返回值。
   * @param {String | Function} to  目标地址，业务系统内相对地址
   */
  async forward(this: Context, to: string | ((url: string) => string)) {
    if (this.request.method.toUpperCase() !== "GET") {
      throw new Error("转发只针对GET请求");
    }

    if (typeof to !== "string" && typeof to !== "function") {
      throw new Error("参数[to]错误，只能是字符串或者返回字符串的函数");
    }

    const prefix = this.request.protocol + "://" + this.header.host;
    let url;
    if (typeof to === "string") {
      url = to.startsWith("/") ? prefix + to : prefix + "/" + to;
    } else {
      const format = to(this.request.url);
      url = format.startsWith("/") ? prefix + format : prefix + "/" + format;
    }

    const target = await this.curl(url);
    this.status = target.status;
    this.set(target.headers as any);
    this.body = target.data;
  }
};
